package com.waterfairy.particle;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.RequiresApi;

import java.util.ArrayList;

public class ObjectMoveSurfaceView extends SurfaceView implements SurfaceHolder.Callback, OnFreshListener {
    private static final String TAG = "ObjectMoveSV";
    private ObjectMoveEngine objectMoveEngine;
    private Canvas canvas;

    public ObjectMoveSurfaceView(Context context) {
        this(context, null);
    }

    public ObjectMoveSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setZOrderOnTop(true);
        getHolder().addCallback(this);
        objectMoveEngine = new ObjectMoveEngine();
        objectMoveEngine.setOnFreshListener(this);
        objectMoveEngine.initPaint();
    }

    public void setBitmapList(ArrayList<Bitmap> arrayList) {
        objectMoveEngine.setBitmapList(arrayList);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        objectMoveEngine.start(false);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        objectMoveEngine.initSize(width, height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        objectMoveEngine.stop();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public synchronized void onFresh() {
        canvas = getHolder().getSurface().lockHardwareCanvas();
        canvas.drawColor(Color.WHITE);
        objectMoveEngine.onDraw(canvas);
        getHolder().getSurface().unlockCanvasAndPost(canvas);
    }
}
